package ai.mspbots.poc.db.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.Arrays;

public class DoubleArrayTypeHandler extends BaseTypeHandler<Double[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Double[] parameter, JdbcType jdbcType) throws SQLException {
        Array array = ps.getConnection().createArrayOf("float8", Arrays.stream(parameter).toArray());
        ps.setArray(i, array);
    }

    @Override
    public Double[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Array array = rs.getArray(columnName);
        return array != null ? (Double[]) array.getArray() : null;
    }

    @Override
    public Double[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Array array = rs.getArray(columnIndex);
        return array != null ? (Double[]) array.getArray() : null;
    }

    @Override
    public Double[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Array array = cs.getArray(columnIndex);
        return array != null ? (Double[]) array.getArray() : null;
    }
}